package com.lxj.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;

/**
 * ConnectPool
 */
public class ConnectPool {
    List<Connection> cs = new ArrayList<>();
    int size;

    public ConnectPool(int size) {
        this.size = size;
        init();
    }


    public void init() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            for (int i = 0; i < size; i++) {
                Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/how2java?charactorEncoding=utf-8","root","root");
                cs.add(c);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 链接
     * @return
     */
    public synchronized Connection getCon() {
        while (cs.isEmpty()) {
            try {
                this.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Connection c = cs.remove(0);
        return c;
    }

    public synchronized void returnCon(Connection c) {
        cs.add(c);
        this.notifyAll();
    }

    public static void main(String[] args) {
        
    }
}